#include <stdio.h> 
#include <stdlib.h> 
#include <pthread.h> 
#include <unistd.h> 
#include <string.h> 
#define DEBUG 1 
  
int num = 0; 
pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; 
pthread_cond_t qready=PTHREAD_COND_INITIALIZER;
/**
#include <pthread.h>  
#include <stdio.h>  
#include <stdlib.h>  
#include <unistd.h> 
#define bool int
#define false 0
#define true 1
#define BUFFER_LENGTH 100

pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_full = PTHREAD_COND_INITIALIZER;

bool producer_wait = false;
bool consumer_wait = false;

int size = 0;
int buffer[BUFFER_LENGTH];
int front=0,rear=-1;

void *producer(void *arg)
{
	while(true)
	{
		pthread_mutex_lock(&mylock);
		if(size == BUFFER_LENGTH)
		{
			printf("buffer is full \n");
			producer_wait =true;
			pthread_cond_wait(&cond_full,&mylock);
			producer_wait = false;
		}

		rear = (rear+1)%BUFFER_LENGTH;
		buffer[rear] = rand()%BUFFER_LENGTH;
		printf("producer product the item %d:%d\n",rear,buffer[rear]);
		++ size;

		if(size == 1)
		{
			while(true)
			{
				if(consumer_wait)
				{
					pthread_cond_signal(&cond_empty);
					break;
				}
			}
		}	

		pthread_mutex_unlock(&mylock);
	}
}

void *consumer(void *arg)
{
	while(true)
	{
		pthread_mutex_lock(&mylock);
		if(size == 0)
		{
			printf("buffer is empty\n");
			consumer_wait = true;
			pthread_cond_wait(&cond_empty,&mylock);
			consumer_wait = false;
		}

		printf("consumer consumes an item %d:%d \n",front,buffer[front]);
		front = (front + 1)%BUFFER_LENGTH;
		-- size;
		if(size == BUFFER_LENGTH-1)
		{
			while(true)
			{
				if(producer_wait)
				{
					pthread_cond_signal(&cond_full);
					break;

				}
			}
		}

		pthread_mutex_unlock(&mylock);
	}
}



int main()
{
	pthread_t producer_id;
	pthread_t consumer_id;

	pthread_create(&producer_id,NULL,producer,NULL);
	pthread_create(&consumer_id,NULL,consumer,NULL);

	sleep(1);
	return 0;
}

**/
void* thread_func(void *arg)
{
    int param = (int) arg;
    int i;
    
    for(i = 0; i < 10; i++)
    {
       // pthread_mutex_lock(&mylock);
        
        while(param != num)
        {  
            pthread_cond_wait(&qready, &mylock);
        }
        printf("%d\n", param);
        printf("%c\n", param + 'A');
        num = (num + 1) % 3;
        
       // pthread_mutex_unlock(&mylock);
        pthread_cond_broadcast(&qready);
    }
    
    return (void *)0;
}

int main(int argc, char* argv[])
{
    int i;
    pthread_t tid[3];
    void *tret;
    
    for(i = 0; i < 3; i++)
    {  
        pthread_create(&tid[i], NULL, thread_func, (void *) i);
    }
    
    for(i = 0; i < 3; i++)
    {
        pthread_join(tid[i], &tret);    
    }
}